%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Markov_Chain.m
% M-Function written for MATLAB 5.0
%
% Chris Bartels
% 10/30/01
% Stat. 516
% University of Washington
%
% This function creates a Markov Chain based on a given transition matrix, P.
%   It uses the current state to index a row of P.  This row is passed into 
%   the Rand_Vect function, which returns a random value based on a probability 
%   vector.  This value becomes the current state, and the process is repeated
%   until the desired chain length is reached.
%
% Input:
%   P - Stochastic probability matrix (must be square with rows that add to 1)
%   initial_state - Initial state of the Markov Chain.  This state corresponds
%                   to one of the rows of P.
%   chain_length - Length of the output.
%
% Output:
%   Chain - Vector containing randomly generated Markov Chain.  The first value
%           will be initial_state and it will have chain_length values.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [Chain] = Markvok_Chain( P, initial_state, chain_length )

sz = size(P);
cur_state = round(initial_state);

%
% Verify that the input parameters are valid
%
if (sz(1) ~= sz(2))
   error('Markov_Chain:  Probability matrix is not square');
end
num_states = sz(1);

if (cur_state < 1) | (cur_state > num_states)
   error('Markov_Chain:  Initial state not defined in P')
end

for i=1:num_states
   if (sum(P(i,:)) ~=1 )
      error('Markov_Chain:  Transition matrix is not valid')
   end
end

%
% Create the Markov Chain 
%
Chain(1) = cur_state;
for i = 1:chain_length
   
   cur_state = Rand_Vect(P(cur_state,:), 1);
   Chain(i) = cur_state;
   
end

